<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,netty," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言在上一篇Netty demo 中，了解了Netty中的客户端和服务端之间的通信。这篇则介绍Netty中的心跳。之前在Mina 中心跳的使用是通过继承 KeepAliveMessageFactory 心跳工厂类而实现的。而在Netty中，提供IdleStateHandler 类，可以实现对三种心跳的检测，分别是readerIdleTime、writerIdleTime和allIdleTime。三">
<meta name="keywords" content="java,netty">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty4 学习笔记之二-客户端与服务端心跳 demo">
<meta property="og:url" content="http://yoursite.com/2017/10/08/Netty4 学习笔记之二-客户端与服务端心跳 demo/index.html">
<meta property="og:site_name" content="xuwujing&#39;s blog">
<meta property="og:description" content="前言在上一篇Netty demo 中，了解了Netty中的客户端和服务端之间的通信。这篇则介绍Netty中的心跳。之前在Mina 中心跳的使用是通过继承 KeepAliveMessageFactory 心跳工厂类而实现的。而在Netty中，提供IdleStateHandler 类，可以实现对三种心跳的检测，分别是readerIdleTime、writerIdleTime和allIdleTime。三">
<meta property="og:image" content="http://img.blog.csdn.net/20171008125728058?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171008125754027?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:updated_time" content="2017-10-08T05:50:51.197Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Netty4 学习笔记之二-客户端与服务端心跳 demo">
<meta name="twitter:description" content="前言在上一篇Netty demo 中，了解了Netty中的客户端和服务端之间的通信。这篇则介绍Netty中的心跳。之前在Mina 中心跳的使用是通过继承 KeepAliveMessageFactory 心跳工厂类而实现的。而在Netty中，提供IdleStateHandler 类，可以实现对三种心跳的检测，分别是readerIdleTime、writerIdleTime和allIdleTime。三">
<meta name="twitter:image" content="http://img.blog.csdn.net/20171008125728058?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/10/08/Netty4 学习笔记之二-客户端与服务端心跳 demo/"/>





  <title>Netty4 学习笔记之二-客户端与服务端心跳 demo | xuwujing's blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?39c177d10f6e05ddfa113e02139b9c1c";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xuwujing's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/10/08/Netty4 学习笔记之二-客户端与服务端心跳 demo/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xuwujing">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/xuwujing.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xuwujing's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty4 学习笔记之二-客户端与服务端心跳 demo</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-08T13:25:13+08:00">
                2017-10-08
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/netty/" itemprop="url" rel="index">
                    <span itemprop="name">netty</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>在<a href="http://blog.csdn.net/qazwsxpcm/article/details/77750865" target="_blank" rel="external">上一篇Netty demo</a> 中，了解了Netty中的客户端和服务端之间的通信。这篇则介绍Netty中的心跳。<br>之前在Mina 中心跳的使用是通过继承 KeepAliveMessageFactory 心跳工厂类而实现的。而在Netty中，提供IdleStateHandler 类，可以实现对三种心跳的检测，分别是readerIdleTime、writerIdleTime和allIdleTime。<br>三个的参数解释如下：<br>1）readerIdleTime：为读超时时间（即测试端一定时间内未接受到被测试端消息）;<br>2）writerIdleTime：为写超时时间（即测试端一定时间内向被测试端发送消息）<br>3）allIdleTime：所有类型的超时时间;</p>
<p>所以在channelPipeline中加入IdleStateHandler，我们在handler中提示的是5秒读，所以我们服务端的配置的是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ph.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));</div></pre></td></tr></table></figure>
<p>因为服务端必须5秒接受一次心跳请求， 那么客户端的配置:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ph.addLast( new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));</div></pre></td></tr></table></figure>
<p>userEventTriggered是Netty 处理心跳超时事件，在IdleStateHandler设置超时时间，如果达到了，就会直接调用该方法。如果没有超时则不调用。我们重写该方法的话，就可以自行进行相关的业务逻辑处理了。</p>
<p>完整的代码如下:</p>
<h3 id="服务端"><a href="#服务端" class="headerlink" title="服务端:"></a>服务端:</h3><p>服务端与之前的demo相比没有什么变化。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line">import io.netty.bootstrap.ServerBootstrap;</div><div class="line">import io.netty.channel.ChannelFuture;</div><div class="line">import io.netty.channel.EventLoopGroup;</div><div class="line">import io.netty.channel.nio.NioEventLoopGroup;</div><div class="line">import io.netty.channel.socket.nio.NioServerSocketChannel;</div><div class="line"></div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: NettyServer</div><div class="line">* Description: Netty服务端</div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月8日</div><div class="line"> */</div><div class="line">public class NettyServer &#123;</div><div class="line">	    private static final int port = 9876; //设置服务端端口</div><div class="line">	    private static  EventLoopGroup group = new NioEventLoopGroup();   // 通过nio方式来接收连接和处理连接   </div><div class="line">	    private static  ServerBootstrap b = new ServerBootstrap();</div><div class="line">	    </div><div class="line">	    /**</div><div class="line">		 * Netty创建全部都是实现自AbstractBootstrap。</div><div class="line">		 * 客户端的是Bootstrap，服务端的则是	ServerBootstrap。</div><div class="line">		 **/</div><div class="line">	    public static void main(String[] args) throws InterruptedException &#123;</div><div class="line">	        try &#123;</div><div class="line">	            b.group(group);</div><div class="line">	            b.channel(NioServerSocketChannel.class);</div><div class="line">	            b.childHandler(new NettyServerFilter()); //设置过滤器</div><div class="line">	            // 服务器绑定端口监听</div><div class="line">	            ChannelFuture f = b.bind(port).sync();</div><div class="line">	            System.out.println(&quot;服务端启动成功,端口是:&quot;+port);</div><div class="line">	            // 监听服务器关闭监听</div><div class="line">	            f.channel().closeFuture().sync();</div><div class="line">	        &#125; finally &#123;</div><div class="line">	            group.shutdownGracefully(); //关闭EventLoopGroup，释放掉所有资源包括创建的线程  </div><div class="line">	        &#125;</div><div class="line">	    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="服务端业务逻辑"><a href="#服务端业务逻辑" class="headerlink" title="服务端业务逻辑"></a>服务端业务逻辑</h3><p>业务逻辑这块，因为要重写userEventTriggered，所以继承ChannelInboundHandlerAdapter 。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div></pre></td><td class="code"><pre><div class="line">import io.netty.channel.ChannelHandlerContext;</div><div class="line">import io.netty.channel.ChannelInboundHandlerAdapter;</div><div class="line">import io.netty.handler.timeout.IdleState;</div><div class="line">import io.netty.handler.timeout.IdleStateEvent;</div><div class="line"></div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: HelloServerHandler</div><div class="line">* Description:  服务端业务逻辑</div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月8日</div><div class="line"> */</div><div class="line">public class NettyServerHandler extends ChannelInboundHandlerAdapter &#123;</div><div class="line">	</div><div class="line">	/** 空闲次数 */</div><div class="line">    private int idle_count =1; </div><div class="line">    /** 发送次数 */</div><div class="line">    private int count = 1;  </div><div class="line">    </div><div class="line">     /**</div><div class="line">      * 超时处理</div><div class="line">      * 如果5秒没有接受客户端的心跳，就触发;</div><div class="line">      * 如果超过两次，则直接关闭;</div><div class="line">      */</div><div class="line">   @Override  </div><div class="line">    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception &#123;  </div><div class="line">        if (obj instanceof IdleStateEvent) &#123;  </div><div class="line">            IdleStateEvent event = (IdleStateEvent) obj;  </div><div class="line">            if (IdleState.READER_IDLE.equals(event.state())) &#123;  //如果读通道处于空闲状态，说明没有接收到心跳命令</div><div class="line">                System.out.println(&quot;已经5秒没有接收到客户端的信息了&quot;);  </div><div class="line">                if (idle_count &gt; 2) &#123;  </div><div class="line">                    System.out.println(&quot;关闭这个不活跃的channel&quot;);  </div><div class="line">                    ctx.channel().close();  </div><div class="line">                &#125;  </div><div class="line">         	idle_count++;  </div><div class="line">            &#125;  </div><div class="line">        &#125; else &#123;  </div><div class="line">            super.userEventTriggered(ctx, obj);  </div><div class="line">        &#125;  </div><div class="line">    &#125;    </div><div class="line">	</div><div class="line">    /**</div><div class="line">     * 业务逻辑处理</div><div class="line">     */</div><div class="line">    @Override  </div><div class="line">    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception &#123;  </div><div class="line">    	System.out.println(&quot;第&quot;+count+&quot;次&quot;+&quot;,服务端接受的消息:&quot;+msg);</div><div class="line">        String message = (String) msg;  </div><div class="line">        if (&quot;hb_request&quot;.equals(message)) &#123;  //如果是心跳命令，则发送给客户端;否则什么都不做</div><div class="line">            ctx.write(&quot;服务端成功收到心跳信息&quot;);  </div><div class="line">            ctx.flush();  </div><div class="line">        &#125;  </div><div class="line">        count++;</div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">    /**</div><div class="line">     * 异常处理</div><div class="line">     */</div><div class="line">    @Override  </div><div class="line">    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception &#123;  </div><div class="line">        cause.printStackTrace();  </div><div class="line">        ctx.close();  </div><div class="line">    &#125; </div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="服务端过滤器"><a href="#服务端过滤器" class="headerlink" title="服务端过滤器"></a>服务端过滤器</h3><p>这块增加了心跳的相关设置。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line">import io.netty.channel.ChannelInitializer;</div><div class="line">import io.netty.channel.ChannelPipeline;</div><div class="line">import io.netty.channel.socket.SocketChannel;</div><div class="line">import io.netty.handler.codec.string.StringDecoder;</div><div class="line">import io.netty.handler.codec.string.StringEncoder;</div><div class="line">import io.netty.handler.timeout.IdleStateHandler;</div><div class="line"></div><div class="line">import java.util.concurrent.TimeUnit;</div><div class="line"> </div><div class="line">/**</div><div class="line">  * </div><div class="line"> * Title: HelloServerInitializer</div><div class="line"> * Description: Netty 服务端过滤器</div><div class="line"> * Version:1.0.0  </div><div class="line"> * @author pancm</div><div class="line"> * @date 2017年10月8日</div><div class="line">  */</div><div class="line">public class NettyServerFilter extends ChannelInitializer&lt;SocketChannel&gt; &#123;</div><div class="line"> </div><div class="line">     @Override</div><div class="line">     protected void initChannel(SocketChannel ch) throws Exception &#123;</div><div class="line">         ChannelPipeline ph = ch.pipeline();</div><div class="line">         // 以(&quot;\n&quot;)为结尾分割的 解码器</div><div class="line">//        ph.addLast(&quot;framer&quot;, new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));</div><div class="line">         // 解码和编码，应和客户端一致</div><div class="line">         //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式</div><div class="line">    	 ph.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));</div><div class="line">         ph.addLast(&quot;decoder&quot;, new StringDecoder());</div><div class="line">         ph.addLast(&quot;encoder&quot;, new StringEncoder());</div><div class="line">         ph.addLast(&quot;handler&quot;, new NettyServerHandler());// 服务端业务逻辑</div><div class="line">     &#125;</div><div class="line"> &#125;</div></pre></td></tr></table></figure></p>
<h3 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h3><p>因为过滤器中没有使用DelimiterBasedFrameDecoder ，所以不必换行了。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line">import io.netty.bootstrap.Bootstrap;</div><div class="line">import io.netty.channel.Channel;</div><div class="line">import io.netty.channel.EventLoopGroup;</div><div class="line">import io.netty.channel.nio.NioEventLoopGroup;</div><div class="line">import io.netty.channel.socket.nio.NioSocketChannel;</div><div class="line">import java.io.IOException;</div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: NettyClient</div><div class="line">* Description: Netty客户端 </div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月8日</div><div class="line"> */</div><div class="line">public class NettyClient &#123;</div><div class="line">    </div><div class="line">    public static String host = &quot;127.0.0.1&quot;;  //ip地址</div><div class="line">    public static int port = 9876;			//端口</div><div class="line">    /// 通过nio方式来接收连接和处理连接   </div><div class="line">    private static EventLoopGroup group = new NioEventLoopGroup(); </div><div class="line">    private static  Bootstrap b = new Bootstrap();</div><div class="line">    private static Channel ch;</div><div class="line">    </div><div class="line">    /**</div><div class="line">	 * Netty创建全部都是实现自AbstractBootstrap。</div><div class="line">	 * 客户端的是Bootstrap，服务端的则是	ServerBootstrap。</div><div class="line">	 **/</div><div class="line">    public static void main(String[] args) throws InterruptedException, IOException &#123; </div><div class="line">        	System.out.println(&quot;客户端成功启动...&quot;);</div><div class="line">            b.group(group);</div><div class="line">            b.channel(NioSocketChannel.class);</div><div class="line">            b.handler(new NettyClientFilter()); </div><div class="line">            // 连接服务端</div><div class="line">            ch = b.connect(host, port).sync().channel();</div><div class="line">            star();</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    public static void star() throws IOException&#123;</div><div class="line">    	String str=&quot;Hello Netty&quot;;</div><div class="line">    	ch.writeAndFlush(str);</div><div class="line">//    	ch.writeAndFlush(str+ &quot;\r\n&quot;);</div><div class="line">    	System.out.println(&quot;客户端发送数据:&quot;+str);</div><div class="line">   &#125;	</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="客户端业务逻辑处理"><a href="#客户端业务逻辑处理" class="headerlink" title="客户端业务逻辑处理"></a>客户端业务逻辑处理</h3><p>简单的在userEventTriggered 做了下相应的逻辑处理。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div></pre></td><td class="code"><pre><div class="line">import io.netty.buffer.ByteBuf;</div><div class="line">import io.netty.buffer.Unpooled;</div><div class="line">import io.netty.channel.ChannelHandlerContext;</div><div class="line">import io.netty.channel.ChannelInboundHandlerAdapter;</div><div class="line">import io.netty.handler.timeout.IdleState;</div><div class="line">import io.netty.handler.timeout.IdleStateEvent;</div><div class="line">import io.netty.util.CharsetUtil;</div><div class="line"></div><div class="line">import java.util.Date;</div><div class="line"></div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: NettyClientHandler</div><div class="line">* Description: 客户端业务逻辑实现</div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月8日</div><div class="line"> */</div><div class="line">public class NettyClientHandler extends  ChannelInboundHandlerAdapter &#123;</div><div class="line">	/** 客户端请求的心跳命令  */</div><div class="line"> 	private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(&quot;hb_request&quot;,  </div><div class="line">            CharsetUtil.UTF_8));  </div><div class="line">      </div><div class="line">    /** 空闲次数 */</div><div class="line">    private int idle_count = 1; </div><div class="line">    </div><div class="line">    /** 发送次数 */</div><div class="line">    private int count = 1;  </div><div class="line">    </div><div class="line">    /**循环次数 */ </div><div class="line">    private int fcount = 1;  </div><div class="line"></div><div class="line">	 /**</div><div class="line">     * 建立连接时</div><div class="line">     */</div><div class="line">    @Override  </div><div class="line">    public void channelActive(ChannelHandlerContext ctx) throws Exception &#123;  </div><div class="line">        System.out.println(&quot;建立连接时：&quot;+new Date());  </div><div class="line">        ctx.fireChannelActive();  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">     /**</div><div class="line">      * 关闭连接时</div><div class="line">      */</div><div class="line">    @Override  </div><div class="line">    public void channelInactive(ChannelHandlerContext ctx) throws Exception &#123;  </div><div class="line">        System.out.println(&quot;关闭连接时：&quot;+new Date());  </div><div class="line">    &#125;  </div><div class="line">    </div><div class="line">    /**</div><div class="line">     * 心跳请求处理</div><div class="line">     * 每4秒发送一次心跳请求;</div><div class="line">     * </div><div class="line">     */</div><div class="line">    @Override  </div><div class="line">    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception &#123;  </div><div class="line">        System.out.println(&quot;循环请求的时间：&quot;+new Date()+&quot;，次数&quot;+fcount);  </div><div class="line">        if (obj instanceof IdleStateEvent) &#123;   </div><div class="line">            IdleStateEvent event = (IdleStateEvent) obj;  </div><div class="line">            if (IdleState.WRITER_IDLE.equals(event.state())) &#123;  //如果写通道处于空闲状态,就发送心跳命令</div><div class="line">                if(idle_count &lt;= 3)&#123;   //设置发送次数</div><div class="line">                    idle_count++;  </div><div class="line">                    ctx.channel().writeAndFlush(HEARTBEAT_SEQUENCE.duplicate());  </div><div class="line">                &#125;else&#123;  </div><div class="line">                	System.out.println(&quot;不再发送心跳请求了！&quot;);</div><div class="line">                &#125;</div><div class="line">                fcount++;</div><div class="line">            &#125;  </div><div class="line">        &#125;  </div><div class="line">    &#125;  </div><div class="line"></div><div class="line">    /**</div><div class="line">     * 业务逻辑处理	</div><div class="line">     */</div><div class="line">    @Override  </div><div class="line">    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception &#123;  </div><div class="line">    	System.out.println(&quot;第&quot;+count+&quot;次&quot;+&quot;,客户端接受的消息:&quot;+msg);</div><div class="line">    	count++;</div><div class="line">    &#125;  </div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="客户端过滤器"><a href="#客户端过滤器" class="headerlink" title="客户端过滤器"></a>客户端过滤器</h3><p>几乎和服务端一致，除了心跳相关设置。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line">import io.netty.channel.ChannelInitializer;</div><div class="line">import io.netty.channel.ChannelPipeline;</div><div class="line">import io.netty.channel.socket.SocketChannel;</div><div class="line">import io.netty.handler.codec.string.StringDecoder;</div><div class="line">import io.netty.handler.codec.string.StringEncoder;</div><div class="line">import io.netty.handler.timeout.IdleStateHandler;</div><div class="line"></div><div class="line">import java.util.concurrent.TimeUnit;</div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: NettyClientFilter</div><div class="line">* Description: Netty客户端 过滤器</div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月8日</div><div class="line"> */</div><div class="line">public class NettyClientFilter extends ChannelInitializer&lt;SocketChannel&gt; &#123;</div><div class="line"></div><div class="line">    @Override</div><div class="line">    protected void initChannel(SocketChannel ch) throws Exception &#123;</div><div class="line">        ChannelPipeline ph = ch.pipeline();</div><div class="line">        /*</div><div class="line">         * 解码和编码，应和服务端一致</div><div class="line">         * */</div><div class="line">//        ph.addLast(&quot;framer&quot;, new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));</div><div class="line">        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式</div><div class="line">        //因为服务端设置的超时时间是5秒，所以设置4秒</div><div class="line">        ph.addLast( new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));  </div><div class="line">        ph.addLast(&quot;decoder&quot;, new StringDecoder());</div><div class="line">        ph.addLast(&quot;encoder&quot;, new StringEncoder());</div><div class="line">        ph.addLast(&quot;handler&quot;, new NettyClientHandler()); //客户端的逻辑</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="效果图"><a href="#效果图" class="headerlink" title="效果图:"></a>效果图:</h2><h3 id="服务端-1"><a href="#服务端-1" class="headerlink" title="服务端:"></a>服务端:</h3><p><img src="http://img.blog.csdn.net/20171008125728058?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<h3 id="客户端-1"><a href="#客户端-1" class="headerlink" title="客户端"></a>客户端</h3><p><img src="http://img.blog.csdn.net/20171008125754027?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<h2 id="其它"><a href="#其它" class="headerlink" title="其它"></a>其它</h2><p>本文只是个简单的心跳测试，所以在细节方面可能有所欠缺。 如有不妥，欢迎指出！</p>
<p>参考:<a href="http://blog.csdn.net/linuu/article/details/51404264" target="_blank" rel="external">http://blog.csdn.net/linuu/article/details/51404264</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/netty/" rel="tag"># netty</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/05/在Github上面搭建一个自己域名的Hexo博客/" rel="next" title="在Github上面搭建一个自己域名的Hexo博客">
                <i class="fa fa-chevron-left"></i> 在Github上面搭建一个自己域名的Hexo博客
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/10/17/Netty4 学习笔记之三-粘包和拆包/" rel="prev" title="Netty4 学习笔记之三-粘包和拆包">
                Netty4 学习笔记之三-粘包和拆包 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/xuwujing.png"
               alt="xuwujing" />
          <p class="site-author-name" itemprop="name">xuwujing</p>
           
              <p class="site-description motion-element" itemprop="description">The way of the future!</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">56</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">36</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xuwujing" target="_blank" title="github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/qazwsxpcm?viewmode=list" target="_blank" title="csdn">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  csdn
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://home.cnblogs.com/u/xuwujing/" target="_blank" title="cnblogs">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  cnblogs
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.woainia.site/" title="woainia" target="_blank">woainia</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="chenssy" target="_blank">chenssy</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端"><span class="nav-number">1.1.</span> <span class="nav-text">服务端:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端业务逻辑"><span class="nav-number">1.2.</span> <span class="nav-text">服务端业务逻辑</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端过滤器"><span class="nav-number">1.3.</span> <span class="nav-text">服务端过滤器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端"><span class="nav-number">1.4.</span> <span class="nav-text">客户端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端业务逻辑处理"><span class="nav-number">1.5.</span> <span class="nav-text">客户端业务逻辑处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端过滤器"><span class="nav-number">1.6.</span> <span class="nav-text">客户端过滤器</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#效果图"><span class="nav-number">2.</span> <span class="nav-text">效果图:</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端-1"><span class="nav-number">2.1.</span> <span class="nav-text">服务端:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端-1"><span class="nav-number">2.2.</span> <span class="nav-text">客户端</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其它"><span class="nav-number">3.</span> <span class="nav-text">其它</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xuwujing</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
